package com.utils;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

import org.apache.struts2.ServletActionContext;

public class CutImage {
	final static String PATH = ServletActionContext.getServletContext().getRealPath("/");
	private static FileInputStream file_in = null;
	private static ImageInputStream img_out = null;
	private static String new_name;
	
	public static String cut(String old_name, int x, int y, int width, int height) throws IOException{
		try {
			new_name = RenameImg.getNewName(old_name);
			file_in = new FileInputStream(PATH + "img/" + old_name);
			Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");
			ImageReader reader = it.next();
			img_out = ImageIO.createImageInputStream(file_in);
			reader.setInput(img_out, true);
			ImageReadParam param = reader.getDefaultReadParam();
			Rectangle rect = new Rectangle(x, y, width, height);
			param.setSourceRegion(rect);
			BufferedImage bi = reader.read(0, param);
			ImageIO.write(bi, "jpg", new File(PATH + "img/" + getNew_name()));
		} finally {
			if (file_in != null)
				file_in.close();
			if (img_out != null)
				img_out.close();
		}
		return getNew_name();
		
	}

	public static FileInputStream getFile_in() {
		return file_in;
	}

	public static void setFile_in(FileInputStream file_in) {
		CutImage.file_in = file_in;
	}

	public static ImageInputStream getImg_out() {
		return img_out;
	}

	public static void setImg_out(ImageInputStream img_out) {
		CutImage.img_out = img_out;
	}

	public static String getNew_name() {
		return new_name;
	}

	public static void setNew_name(String new_name) {
		CutImage.new_name = new_name;
	}
	
	
	 

}
